;
(function () {
  hlSelectUi(true)

  new Vue({
    el: '#costItemIndex',
    data: {
      quanxian: JSON.parse(localStorage.getItem('permissions')),
      keyword: '',
      data: [],
      totalPage: 0,
      totalZnjPage: 0,
      totalCount: 0,
      totalZnjCount: 0,
      currentPage: 1,
      currentZnjPage: 1,
      limit: ['10'],
      limitZnj: ['5'],
      flag: true,
      pageNums: [{
        name: '10',
        code: '10'
      }, {
        name: '15',
        code: '15'
      }, {
        name: '20',
        code: '20'
      }],
      pageZnjNums: [{
        name: '5',
        code: '5'
      }, {
        name: '10',
        code: '10'
      }, {
        name: '15',
        code: '15'
      }, {
        name: '20',
        code: '20'
      }],
      getINFO: {
        id: '',
        lateFee: '',
        memo: '',
        name: '',
        type: '请选择费项'
      },
      costItemId: '',
      unitList: [], //计量单位
      unitList_p: [],//周期性费项
      unitList_o: [],//一次性费项
      selectUnitCode: '', //选中的计量单位
      typeText: '',
      HlValidator: '',
      typeList: [],
      searchTypeSelect: [], //选中的费项类型(查询)
      newTypeSelect: ['S'], //选中的费项类型（新增）
      sysCostList: [], //系统费项列表
      newCostItem: {
        type: [], //选中的费项(系统费项)
        code: [], //系统费项名称
        name: '', //一次和周期费项名称
        unitsVal: [], //计量单位
        rate: '', //税率
        lateFee: '', //滞纳金
        memo: '',
      },

      menuType: 'fx', //顶部菜单，默认费项（fx）
      autoCal: [{
        code: 'Y',
        name: '开'
      },
      {
        code: 'N',
        name: '关'
      }
      ],
      calType: [{
        code: 'A',
        name: '全额'
      },
      {
        code: 'B',
        name: '差额'
      }
      ],

    },
    filters: {
      lateState: function (str) {

        if (str == '请选择费项') {
          return '请选择费项'
        }
        return str == 'O' ? '一次性费项' : (str == 'P' ? '周期性费项' : '系统费项');
      },
      czState: function (str) {
        return str == 'Y' ? '启用' : '停用';
      },
      toDou: function (n) {
        return n < 10 ? '0' + n : '' + n;
      }
    },
    methods: {
      // 校验起算日期
      checkDate(val, index) {
        if (val < 1) {
          hl.toast('天数需大于0')
          this.data[index].lateFeeCalculateDate = 1
        }
      },
      // 保存滞纳金前校验
      checkSaveFun() {
        let flag = false
        this.data.map(item => {
          if (item.lateFeeCalculateFlag + '' == 'Y') {
            flag = true
          }
        })
        if (flag) {
          hllayer.confirm2('<div class="dialog-up">检测到开启自动计算滞纳金，是否保存并清除当前所有未完结账单应收滞纳金。</div><div class="dialog-down">注：保存后，次日生效，当日账单，请手动处理。</div>', () => {
            this.saveFun('Y')
          })
        } else {
          this.saveFun()
        }
      },
      // 保存滞纳金
      saveFun(val) {
        let data = {
          clear_late_fee_flag: val ? 'Y' : 'N',
          late_fee_configs: []
        }
        this.data.map(item => {
          data.late_fee_configs.push({
            id: item.id,
            late_fee: item.lateFee || '0',
            latefee_calculate_flag: item.lateFeeCalculateFlag + '',
            latefee_calculate_date: item.lateFeeCalculateDate + '',
            latefee_calculate_method: item.lateFeeCalculateMethod + ''
          })
        })
        data.late_fee_configs = JSON.stringify(data.late_fee_configs)
        hlhttp.put({
          url: 'expenditure/late_fee',
          data: data,
          success: res => {
            hl.toast('保存成功')
            this.getCostZnjData()
          },
        })
      },
      // 切换顶部菜单
      switchMenu(val) {
        this.menuType = val
        this.limit = ['10']
        this.limitZnj = ['5']
        this.totalPage = 0
        this.totalZnjPage = 0
        this.totalCount = 0
        this.totalZnjCount = 0
        this.currentPage = 1
        this.currentZnjPage = 1
        if (val == 'znj') {
          this.getCostZnjData()
        } else {
          this.getCostData()
        }
      },

      // 新增系统费项下的费项名称
      selectName(val) {
        console.log(val)
      },
      //新增选中费项类型
      handleClick(val) {

      },
      setunitsVal(arr) {
        console.log(arr)
        this.newCostItem.unitsVal = [arr[0].code]
      },
      // 查询
      search() {
        this.getCostData()
      },
      // 重置
      reset() {
        this.limit = ['10']
        this.keyword = ''
        this.searchTypeSelect = []
        this.getCostData();
      },
      // 获取费项类型
      getTypeList() {
        var that = this

        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'CMMN',
            config_name: 'CM_EXPENDITURE_TYPE'
          },
          success: function (res) {
            res.map((item, index) => {
              item.name = item.dictName
              item.code = item.dictCode
              if (item.dictCode == 'S') {
                that.sysCostList = JSON.parse(item.dictValue).value
              }
            })
            that.typeList = res
            that.sysCostList.map(item => {
              item.name = item.dictName
              item.code = item.dictCode
            })
          },
        })
      },
      //新增费项
      newAddCost() {
        this.flag = false
        this.typeText = '新增'
        this.newTypeSelect = ["S"]
        this.newCostItem = {
          type: [], //选中的费项类型(新增)
          code: '',
          name: '',
          unitsVal: [],
          rate: '',
          lateFee: '',
          memo: '',
        }
      },
      // 权限控制
      permission: function () {
        var self = this;
        var show = function () {
          if ($('.js-state').hasClass('js-access-control') && $('.js-edit').hasClass('js-access-control')) {
            $('.js-state').parent().text('--')
          }
        }
        loginPrem.loginList(show)
      },
      //获取计量单位
      getUnitList() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'CMMN',
            config_name: 'CM_EXPENDITURE_UNIT'
          },
          success: res => {
            res.map(item => {
              if (item.dictProperty) {
                item.systemDefaultFlag = JSON.parse(item.dictProperty).systemDefaultFlag
              } else {
                item.systemDefaultFlag = 'N'
              }
              item.name = item.dictName
              item.code = item.dictCode
              this.unitList_p.push(item)
              if (item.systemDefaultFlag == 'N') {
                this.unitList_o.push(item)
              }
            })
          },
        })
      },
      // 选择费项类型
      handleClick() {
        if (this.newTypeSelect + '' == 'P') {
          this.unitList = this.unitList_p
        }
        if (this.newTypeSelect + '' == 'O') {
          this.unitList = this.unitList_o
        }
      },
      selectUnit(item) {
        this.getINFO.unitsCode = item.dictCode
      },
      turnPage(item) {
        this.limit = [item[0].code];
        this.currentPage = 1
        this.getCostData()
      },
      turnZnjPage(item) {
        this.limitZnj = [item[0].code];
        this.currentZnjPage = 1
        this.getCostZnjData()
      },
      handlePageChange(num) {
        this.getCostData()
      },
      handleZnjPageChange(num) {
        this.getCostZnjData()
      },
      //获取数据(费项板块)
      getCostData: function () {
        var self = this;
        hlhttp.get({
          url: 'expenditures',
          data: {
            keyword: self.keyword || '#',
            type: self.searchTypeSelect.length ? self.searchTypeSelect.join('') : '#',
            flow_type: '#',
            page: self.currentPage,
            limit: self.limit[0]
          },
          success: function (res) {
            self.totalCount = res.totalCount
            self.totalPage = res.totalPage
            self.data = res.expenditures
            self.permission()
          }
        })
      },
      // 获取数据（滞纳金板块）
      getCostZnjData: function (val) {
        var self = this;
        hlhttp.get({
          url: 'expenditures',
          data: {
            keyword: '#',
            type: '#',
            flow_type: '#',
            page: self.currentZnjPage,
            limit: self.limitZnj[0]
          },
          success: function (res) {
            res.expenditures.map(item => {
              item.lateFeeCalculateFlag = [item.lateFeeCalculateFlag] || ['N']
              item.lateFeeCalculateDate = item.lateFeeCalculateDate || 1
              item.lateFeeCalculateMethod = [item.lateFeeCalculateMethod] || ['C']
            })
            self.totalZnjCount = res.totalCount
            self.totalZnjPage = res.totalPage
            self.data = res.expenditures
          }
        })
      },
      //启用停用
      czValid: function (id, state) {
        const self = this;

        hlhttp.put({
          url: 'expenditures/valid_state',
          data: {
            expenditure_id: id,
            opt: state
          },
          success: function () {
            self.getCostData()
          }
        })
      },
      //编辑
      editCostItem: function (id, flag) {
        this.costItemId = id
        var that = this;
        this.flag = flag;
        this.typeText = '编辑'

        hlhttp.get({
          url: 'expenditure',
          data: {
            id: id
          },
          success: function (data) {
            that.newTypeSelect = []

            if (data.type == "R" || data.type == "CM" || data.type == "D") {
              that.newTypeSelect.push("S")
              that.newCostItem = {
                type: [data.type],
                code: data.name, //系统费项名称
                unitsVal: [data.unitsCode], //计量单位
                rate: data.taxFee, //税率
                lateFee: data.lateFee, //滞纳金
                memo: data.memo,
              }
            } else {
              that.newTypeSelect.push(data.type)
              that.handleClick()
              that.newCostItem = {
                type: data.type,
                name: data.name, //一次和周期费项名称
                unitsVal: [data.unitsCode], //计量单位
                rate: data.taxFee, //税率
                lateFee: data.lateFee, //滞纳金
                memo: data.memo,
              }
            }
          }
        })
      },
      editExpense: function (id) {
        var self = this;
        var validateRes = self.validation()
        if (!validateRes) {
          return false;
        }

        hlhttp.put({
          url: 'expenditure',
          data: {
            "expenditure_id": self.costItemId,
            "type": self.newTypeSelect.join('') != 'S' ? self.newTypeSelect.join('') : self.newCostItem.type.join(''), //费项类型
            "name": self.newTypeSelect.join('') != 'S' ? self.newCostItem.name : self.newCostItem.code, //费项名
            "tax_fee": self.newCostItem.rate,
            "late_fee": self.newCostItem.lateFee || '#', //滞纳金比例，不填传0
            "memo": self.newCostItem.memo || '#', //费项说明
            "units_code": self.newTypeSelect.join('') != 'S' ? self.newCostItem.unitsVal.length ? self.newCostItem.unitsVal[0] : '#' : '#' //单位code
          },
          success: function () {
            self.currentPage = 1
            self.getCostData()
            self.close()
          }
        })
      },
      //系统费项新增选中费项名称
      setName(val) {
        this.newCostItem.code = val[0].name
        this.newCostItem.type = [val[0].code]
      },
      //验证
      validation: function () {
        if (this.newTypeSelect.join('') != 'S') {
          if (!this.newCostItem.name) {
            hl.toast('请输入费项名称');
            return
          }
          if (!this.newCostItem.unitsVal[0]) {
            hl.toast('请输入计量单位');
            return
          }
        } else {
          if (!this.newCostItem.type.length) {
            hl.toast('请输入费项名称');
            return
          }
        }

        this.HlValidator.add(this.newCostItem.rate, [{
          rule: 'isEmpty',
          msg: '请输入税率'
        },
        {
          rule: 'isScale',
          msg: '请输入正确税率'
        }
        ])

        var errorMsg = this.HlValidator.start()
        if (errorMsg != true) {
          hl.toast(errorMsg)
          return false
        }
        // this.HlValidator.add(this.newCostItem.lateFee, [{
        //     rule: 'isEmpty',
        //     msg: '请输入滞纳金比例'
        //   },
        //   {
        //     rule: 'isScale',
        //     msg: '请输入正确滞纳金比例'
        //   }
        // ])
        var errorMsg = this.HlValidator.start()
        if (errorMsg != true) {
          hl.toast(errorMsg)
          return false
        }
        return true
      },
      //新建
      createExpense: function (flag) {
        const self = this;
        var validateRes = self.validation()
        if (!validateRes) {
          return false;
        }

        hlhttp.post({
          url: 'expenditure',
          data: {
            "type": self.newTypeSelect.join('') != 'S' ? self.newTypeSelect.join('') : self.newCostItem.type.join(''), //费项类型
            "name": self.newTypeSelect.join('') != 'S' ? self.newCostItem.name : self.newCostItem.code, //费项名
            "tax_fee": self.newCostItem.rate,
            "late_fee": self.newCostItem.lateFee || '#', //滞纳金比例，不填传0
            "memo": self.newCostItem.memo || '#', //费项说明
            "units_code": self.newTypeSelect.join('') != 'S' ? self.newCostItem.unitsVal.length ? self.newCostItem.unitsVal[0] : '#' : '#' //单位code
          },
          success: function () {
            self.currentPage = 1
            self.getCostData()
            self.close()
          }
        })
      },
      //滞空
      close: function () {
        this.flag = true;
      }
    },
    mounted: function () {
      this.getCostData()
      this.getUnitList()
      this.getTypeList()
      this.HlValidator = new HlValidator()
    }
  })
}())
